package jmine.tec.report.domain;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Map.Entry;

import javax.persistence.Entity;
import javax.persistence.JoinTable;
import javax.persistence.OneToMany;
import javax.persistence.Transient;

import org.hibernate.annotations.Cascade;
import org.hibernate.annotations.CascadeType;

/**
 * @author takeshi
 */
@Entity
public class PersistableCurriedDataColumn extends PersistableDataColumn {

    private List<PersistableTuple> tuples = new ArrayList<PersistableTuple>();

    private Map<String, Object> parameters;

    /**
     */
    public PersistableCurriedDataColumn() {
    }

    /**
     * C`tor
     * 
     * @param key the key
     * @param owner the owner
     * @param curried the curried parameters
     */
    public PersistableCurriedDataColumn(String key, PersistableTableDescriptor owner, Map<String, Object> curried) {
        super(key, owner);
        this.parameters = new HashMap<String, Object>(curried);
        Set<Entry<String, Object>> entrySet = this.parameters.entrySet();
        for (Entry<String, Object> entry : entrySet) {
            this.tuples.add(new PersistableTuple(entry.getKey(), entry.getValue()));
        }
    }

    /**
     * @return the parameters
     */
    @Transient
    public Map<String, Object> getParameters() {
        if (this.parameters == null) {
            this.parameters = new HashMap<String, Object>(this.getTuples().size());
            for (PersistableTuple tuple : this.getTuples()) {
                this.parameters.put(tuple.head(), tuple.tail());
            }
        }
        return this.parameters;
    }

    /**
     * @return the tuples
     */
    @JoinTable(name = "PERSISTABLE_PARAMS")
    @OneToMany
    @Cascade({ CascadeType.ALL, CascadeType.DELETE_ORPHAN })
    public List<PersistableTuple> getTuples() {
        return this.tuples;
    }

    /**
     * @param tuples the tuples to set
     */
    protected void setTuples(List<PersistableTuple> tuples) {
        this.tuples = tuples;
    }

}
